package cool.mtc.security.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cool.mtc.core.result.Result;
import cool.mtc.web.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 明河
 */
public interface HandleSupport {
    Logger LOGGER = LoggerFactory.getLogger(HandleSupport.class);
    ObjectMapper MAPPER = new ObjectMapper();

    default <T> void responseData(T t) {
        this.response(Result.ofData(t));
    }

    default <T> void response(Result<T> result) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        String requestUri = request.getRequestURI();
        try {
            String content = MAPPER.writeValueAsString(result);
            assert response != null;
            HttpUtil.writeToResponse(response, content);
            LOGGER.debug("请求地址：{}，响应：{}", requestUri, content);
        } catch (JsonProcessingException ex) {
            LOGGER.error("请求地址：{}，对象序列化 - 失败 - 错误信息：{} - 对象信息: {}", requestUri, ex.getMessage(), result.toString());
        } catch (IOException ex) {
            LOGGER.error("请求地址：{}，HTTP响应错误", requestUri, ex);
        }
    }
}
